package com.rose.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.rose.common.constant.ProductConstant;
import com.rose.mall.product.dao.AttrAttrgroupRelationDao;
import com.rose.mall.product.dao.AttrGroupDao;
import com.rose.mall.product.dao.CategoryDao;
import com.rose.mall.product.entity.AttrAttrgroupRelationEntity;
import com.rose.mall.product.entity.AttrGroupEntity;
import com.rose.mall.product.entity.CategoryEntity;
import com.rose.mall.product.service.AttrAttrgroupRelationService;
import com.rose.mall.product.service.CategoryService;
import com.rose.mall.product.vo.AttrGroupRelationVo;
import com.rose.mall.product.vo.AttrRespVo;
import com.rose.mall.product.vo.AttrVo;
import jodd.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rose.common.utils.PageUtils;
import com.rose.common.utils.Query;

import com.rose.mall.product.dao.AttrDao;
import com.rose.mall.product.entity.AttrEntity;
import com.rose.mall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * SELECT attr_id FROM `pms_attr` WHERE attr_id IN (?) AND search_type = 1
     */
    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        return baseMapper.selectSearchAttrIds(attrIds);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.save(attrEntity);


        // 找寻出刚刚插入属性的id
//        AttrEntity attr_name = this.getOne(new QueryWrapper<AttrEntity>().eq("attr_name", attr.getAttrName()));

        // todo  这块不清楚为什么保存了之后id 就自动的存储进去了
        // 保存其他的分类表  对于销售属性是不保存的
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() &&attr.getAttrGroupId()!=null){
            attrAttrgroupRelationService.addRelation(attr.getAttrGroupId(),attrEntity.getAttrId());

        }


    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId, String type) {

        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type","base".equalsIgnoreCase(type)? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode() );
        if (catelogId != 0){
            wrapper.eq("catelog_id",catelogId);
        }
        String  key = (String)params.get("key");
        if (!StringUtil.isEmpty(key)){
            // 这块就是我的草率了
            wrapper.and((item)->{
                item.eq("attr_id",key)
                        .or()
                        .like("attr_name",key);
//                item.like("attr_name",key);
            });

        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> respVoList = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            // 1.需要 设置分类和分组的名字

            // 如过type == base 才会有分组这一说
            if ("base".equalsIgnoreCase(type)){
                AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                // 感觉这块如果type = sale 的话，关联表查出来就是null ，就不会有下一步了
                // 但是如果测试数据有问题，这块存在关联表，且表的那个值为null，那么在get 的时候会出现问题的吗
                if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    if ( attrGroupEntity != null){
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }

                }
            }


            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());

            }

            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(respVoList);

        return pageUtils;
    }

    /**
     * 传入AttrEntity，在Category表里面查询，返回一个list
     * 看来这块是每次都传入的都一样
     * @param cat_id
     */
    public void getCatelogPath(CategoryEntity cat_id ){
        List list = new ArrayList<>();
        if (cat_id != null){
            // 接下来完成相关的CatelogPath填充
            list.add(cat_id.getCatId());
            Long parentCid = cat_id.getParentCid();
            if (parentCid != null){
                this.getCatelogPath(categoryDao.selectOne(new QueryWrapper<CategoryEntity>().eq("cat_id", parentCid)));
            }else{
                return;
            }
        }


    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity byId = this.getById(attrId);
        AttrRespVo respVo = new AttrRespVo();
        BeanUtils.copyProperties(byId,respVo);


        // 设置分类信息
        Long catelogId = byId.getCatelogId();
        Long[] catelogPath = categoryService.findCateLogPath(catelogId);
        respVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null) {
            respVo.setCatelogName(categoryEntity.getName());
        }
        // 如果是基本的信息， 就没有必要了
        if (byId.getAttrId() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            // 分组信息的设置
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (relationEntity != null){
                respVo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if ( attrGroupEntity != null){
                    respVo.setGroupName(attrGroupEntity.getAttrGroupName());

                }
            }
        }




        return respVo;
    }
    @Transactional
    @Override
    public void updateAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.updateById(attrEntity);

        // 基本类型才进行修改
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 修改分组关联
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            // 设置的需要更新的值
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            relationEntity.setAttrId(attrVo.getAttrId());
            // 查询 attr_id 在 pms_attr_attrgroup_relation 表中是否已经存在 不存在返回0 表示这是添加 反之返回1 为修改 [这里的修改可以修复之前没有设置上的属性]
            Integer count = relationDao.selectCount(new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
            if(count > 0){
                relationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
            }else {
                relationDao.insert(relationEntity);
            }
        }
    }

    /**
     * 根据分组id查出关联表所有属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {

        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        if (relationEntities == null || relationEntities.size() == 0){
            return null;

        }
        List<AttrEntity> collect = relationEntities.stream().map((item) -> {
            AttrEntity attrEntity = this.baseMapper.selectById(item.getAttrId());
//            entities.add(attrEntity);
            return attrEntity;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        // 这种写法会提交很多个删除请求 希望只发送一次请求
//        Arrays.stream(vos).map((item)->{
//            relationDao.delete(new QueryWrapper<AttrAttrgroupRelationEntity>()
//                    .eq("attr_id",item.getAttrId())
//                    .eq("attr_group_id",item.getAttrGroupId()));
//            return null;
//        }
//        );
        List<AttrAttrgroupRelationEntity> collect = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        relationDao.deleteBatchRelation(collect);

    }

    /**
     * 获取当前分组没有关联的所有属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        // 1.当前分组只能关联自己所属分类里面的属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        // 2.当前分组只能关联别的分组没有引用的信息
        //(2.1)当前分类(attr)下的其他分组(group)

        // .ne("attr_group_id",attrGroupEntity.getAttrGroupId()) 不能加上分组的id 不能是自己
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> collect = group.stream().map((item) -> {
            Long attrGroupId = item.getAttrGroupId();
            return attrGroupId;
        }).collect(Collectors.toList());
        //(2.2)这些分组的其他属性
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));
        List<Long> collect1 = attrAttrgroupRelationEntities.stream().map((item) ->
             item.getAttrId()
        ).collect(Collectors.toList());

        //(2.3)从当前分类的所有属性中移除这些属性
        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId)
                .eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());

        if (collect1 != null &&collect1.size() > 0){
            attrEntityQueryWrapper.notIn("attr_id", collect1);
        }
        String key = (String) params.get("key");
        if(!StringUtil.isEmpty(key)){
            attrEntityQueryWrapper.and((w)->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), attrEntityQueryWrapper);
        return new PageUtils(page);
    }

}